<?php

/**
 * 资讯类
 */
class groupModel
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /*
     * 获取群组资料
     * @return $array
    */
    public function getGroupInfo($gid, $update = FALSE)
    {
        !$update && $result = $this->redis->hgetall(REDIS_PREFIX.'GroupInfo_'.$gid);

        if($update || empty($result))
        {
            $result = $this->db->getRow("select * from r_group where gid = '{$gid}'");

            if(!empty($result))
            {
                unset($result['id']);
                $this->redis->hmset(REDIS_PREFIX.'GroupInfo_'.$gid, $result);
            }
        }

        empty($result) && $result = [];

        return $result;
    }
    /*
     * 设置群组资料
     * @return $array
    */
    public function setGroupInfo($gid, $groupInfo=array())
    {
        $result = false;
        if(empty($groupInfo) || !$gid)
        {
            return $result;
        }
        if(!isset($groupInfo['gid'])) $groupInfo['gid'] = $gid;
        if(isset($_FILES['header']))
        {
            $groupImg = $this->uploadGroupHeader('header', md5('group'.time().common::getHashStr(6)));
            is_array($groupImg) && extract($groupImg);
            $header && $groupInfo['header'] = $header;
            $sourceImg && $groupInfo['sourceImg'] = $sourceImg;
        }
        if($id = $this->db->insertRowTable('r_group', $groupInfo))
        {
            $indexData = array('id'=>$id,'name'=>$groupInfo['name'],'gid'=>$gid);
            $this->base->load('xunSearch')->init('group')->delIndex($gid,"gid");
            $this->base->load('xunSearch')->init('group')->addIndex($indexData);
            $this->redis->hmset(REDIS_PREFIX.'GroupInfo_'.$gid, $groupInfo);
            $result = true;
        }
        return $result;
    }
    /*
     * 搜索群组
     * @return $array
    */
    public function searchGroup($keyword, $limit = 1)
    {
        $result = array();
        if($limit == 1)
        {
            $groupInfo = $this->getGroupInfo($keyword);
            if($groupInfo && $groupInfo['isDismiss'] == 0)
            {
                $groups[] = $keyword;
            }
        }
        else
        {
            $groups = $this->db->getCol("select gid from r_group where (gid = '{$keyword}' or name like '%{$keyword}%') and isDismiss = 0 order by gid DESC limit $limit");
        }
        if(!empty($groups))
        {
            $uid = $this->base->uid;
            $groupStatus = $this->getGroupStatus($uid);
            foreach ($groups as $gid)
            {
                $groupInfo = $this->getGroupInfo($gid);
                if($groupInfo && $groupInfo['isDismiss'] == 0)
                {
                    $result[] = array('gid' => $groupInfo['gid'],
                             'name' => $groupInfo['name'],
                             'header' => $groupInfo['header'],
                             'slogan' => $groupInfo['slogan'],
                             'role' => $this->getGroupRole($gid, $uid),
                             'status' => isset($groupStatus[$gid]) ? $groupStatus[$gid] : '7'
                    );
                }
            }
        }
        return $result;
    }
    /*
     * 获取用户与群组的关系
     * int $uid 用户id
     * int $gid 群组id
     * @return $array
    */
    public function getGroupStatus($uid, $gid = 0)
    {
        $result = array();

        $sql = $gid > 0 ? "select gid, status from r_group_add where gid ='{$gid}' and uid = '{$uid}' and isShow = 1" : "select gid, status from r_group_add where uid = '{$uid}' and isShow = 1";

        $status = $this->db->getAll($sql);
        if($status)
        {
            foreach ($status as $v)
            {
                $result[$v['gid']] = $v['status'];
            }
        }

        if($gid > 0)
        {
            if($result)
            {
                $result = $result[$gid];
            }
            else
            {
                $result = '7';
            }
        }
        else
        {
            $result = '7';
        }

        return $result;
    }
    /*
     * 创建群组
     * array $invitee
     * @return $array
    */
    public function createGroup($uid, $name, $slogan='', $province='', $city='', $invitee='[]', $verify=0, $isDismiss=0, $memberLimit = 0, $isBreakAll = TRUE)
    {
        extract($this->uploadGroupHeader('header', md5('group'.time().common::getHashStr(6))));
        $groupInfo = array('uid'        => $uid,
                           'name'       => $name,
                           'slogan'     => $slogan,
                           'province'   => $province,
                           'city'       => $city,
                           'header'     => $header,
                           'sourceImg'  => $sourceImg,
                           'addtime'    => time(),
                           'members'    => 0,
                           'isDismiss'   => $isDismiss,
                           'isverify'     => $verify,
                           'member_limit' => $memberLimit ? $memberLimit : $this->base->config['group']['maxMember'],
                    );
        do
        {
            $gid = $this->getGid();
            $groupInfo['gid'] = $gid;
            $setStr = common::arrayToString($groupInfo);
            $id = $this->db->query("insert into r_group set {$setStr}", 'SILENT');
            $error_no = $this->db->errno();
            if ($error_no > 0 && $error_no != 1062)
            {
                $_ENV['error']->getErrors(100);
                exit;
            }
            //创建im群组(chang) --- IM 
            $rst = $this->base->load('message')->groupCreate($uid, $gid, $name);
        }
        while ($error_no == 1062); //如果是群组号重复则重新提交数据
        //$this->base->result['result'] = compact('gid', 'header', 'sourceImg', 'name','slogan','verify');
       //$isBreakAll && $this->base->breakCall();
        $this->redis->hmset(REDIS_PREFIX.'GroupInfo_'.$gid, $groupInfo);
        // 将群主加入群组
        $this->joinGroup($gid, $uid);
        $this->redis->zadd(REDIS_PREFIX."MGRankList_".$uid,0,$gid);
        // 发送群组邀请
        $this->groupInvite($uid, $gid, $invitee);
//        $key = $this->getCityKey($groupInfo['province'],$groupInfo['city']);
//        !empty($key) && $this->redis->sadd($key,$gid);//同城群组
        $this->base->load('xunSearch')->init('group')->addIndex(array('id'=>$id,'gid'=>$gid,'name'=>$name));
        return compact('gid', 'header', 'sourceImg', 'name','slogan','verify');
    }
    /*
     * 获取一个增量的群组ID gid
     * @return int
    */
    private function getGid()
    {
        $redisKey = REDIS_PREFIX.'IncGroupId';
        $gid = $this->redis->get($redisKey);

        if(empty($gid))
        {
            $gid = 10300;
            $this->redis->set($redisKey, $gid +1);
        }
        else
        {
            // 保留群组IDs
            $backGids = [34567,31111,32222,33333,35555,36666,37777,38888,39999];

            while(TRUE)
            {
                $gid = $this->redis->incrby($redisKey, 1);

                if(!in_array($gid, $backGids))
                {
                    break;
                }
            }
        }

        return $gid;
    }
    /*
     * 获取可再创建的群组数量
     * int $uid
     * @return int $num
    */
    public function getVaileGroupNum($uid)
    {
        if($uid == 175701){
            return 1;
        }else{
            $num = $this->getMaxGroupNum($uid);
            return $num - $this->redis->hget(REDIS_PREFIX.'GroupCreateNum', $uid);
        }

    }
    /*
     * 获取用户在群组中角色
     * int $gid
     * int $uid
     * @return int $num
    */
    public function getGroupRole($gid, $uid)
    {
        $role = $this->redis->hget(REDIS_PREFIX.'GroupRole_'.$gid, $uid);
        return $role === false ? -1 : $role;
    }
    /*
     * 获取可创建的群组最大数量
     * int $uid
     * @return int $num
    */
    public function getMaxGroupNum($uid)
    {
        $num = 3;
        $vipUser = array(14935,21331, 166296, 175701);
        if(in_array($uid, $vipUser))
        {
            $num = 20;
        }

        return $num;
    }
    /*
     * 将某用户加入群组
     * int $gid  群组ID
     * int $uid 用户id
     * boolen   $inform  是否通知
     * @return int
    */
    public function joinGroup($gid, $uid, $manager = 0)
    {
        $result = false;
        $groupInfo = $this->getGroupInfo($gid);
        if(empty($gid) || empty($uid) || empty($groupInfo))
        {
            return $result;
        }

        $maxMember = !empty($groupInfo['member_limit']) ? $groupInfo['member_limit'] : $this->base->config['group']['maxMember'];

        if($groupInfo['members'] >= $maxMember)
        {
            $_ENV['error']->getErrors(910);
            exit;
        }
        $time = $this->base->time;
        $isHost = $uid == $groupInfo['uid'] ? 1 : 0;
        $groupAdd = array('gid' => $gid,
                          'uid' => $uid,
                          'status' => 0,
                          'lastupdate' => $time,
                          );
        empty($groupAdd) && $groupAdd['manager'] = $manager;
        $isHost == 1 && $groupAdd['addtime'] = $time;
        if($this->db->updateRowTable('r_group_add', $groupAdd))
        {
            $groupMem = array('gid' => $gid,
                          'uid' => $uid,
                          'role' => $isHost == 1 ? 1 : 0,
                          'addtime' => $time,
                          'lastupdate' => $time,
                    );
            $result = $this->db->insertRowTable('r_gmember', $groupMem) != false ? true : false;
            if($result)
            {
                $this->db->update("update r_group set members = members+1 where gid = '{$gid}'");
                $isHost == 1 && $this->redis->hset(REDIS_PREFIX.'GroupHost', $gid, $uid);
                if($isHost == 1)
                {
                    $this->redis->hset(REDIS_PREFIX.'GroupHost', $gid, $uid);
                    $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, $time * 3, $uid); //加入群成员列表
                }
                else
                {
                    $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, $time, $uid);
                }
                $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $uid, $groupMem['role']); //群成员身份标识
                $this->redis->HINCRBY(REDIS_PREFIX.'GroupInfo_'.$gid, 'members', 1);
                $this->redis->zadd(REDIS_PREFIX.'MGList_'.$uid, $time, $gid); // 我的群组列表
                if($isHost == 1)
                {
                    $this->redis->zadd(REDIS_PREFIX.'MGListBR_'.$uid, $time + 3000000000, $gid); // 我的群组列表
                }
                else
                {
                    $this->redis->zadd(REDIS_PREFIX.'MGListBR_'.$uid, $time, $gid); // 我的群组列表
                }
                $isHost == 1 && $this->redis->HINCRBY(REDIS_PREFIX.'GroupCreateNum', $uid, 1);  // 用户创建的群组数+1
                $gtotal = $this->redis->hget(REDIS_PREFIX.'GRTotal',$gid);
                $this->redis->zadd(REDIS_PREFIX."MGRankList_".$uid,$gtotal,$gid);
                //加入IM群组
                $this->base->load('message')->groupJoin($uid, $gid , $groupInfo['name']);
                
            }
        }
        return $result;
    }
    /*
     * 向用户发群组邀请
     * int $manager 邀请人ID
     * int $gid  群组ID
     * array $invitee 群组邀请的接收者
     * @return boolen
    */
    public function groupInvite($manager, $gid, $invitee)
    {
        if(!is_array($invitee) || empty($invitee))
        {
            return false;
        }

        //获取发起人的角色
        $managerRole = $this->getGroupRole($gid, $manager);

        $time = time();
        foreach ($invitee as $uid) {
            $role = $this->getGroupRole($gid, $uid);
            if($role >= 0 && $role <= 2)
            {
                continue;
            }

            //如果发起者的角色是群主、或管理员
            if(1 == $managerRole || 2 == $managerRole){
                $status = 4;
                $descType = 'G3';
                $manager_id = $manager;
                $invite_id = "";
            }

            //如果发起者的角色是普通用户
            if(0 == $managerRole){
                $status = 8;
                $descType = 'G10';
                $manager_id = "";
                $invite_id = $manager;
            }
            
            $groupAdd = array('gid' => $gid,
                              'manager' => $manager_id,
                              'uid' => $uid,
                              'status' => $status,
                              'addtime' => $time,
                              'lastupdate' => $time,
                              'invite_id' => $invite_id,
                          );
            if($this->db->updateRowTable('r_group_add', $groupAdd))
            {
                $msg = array('uid' => $manager,
                             'gid' => $gid);
                $this->redis->zadd(REDIS_PREFIX.'GInvite_'.$uid, $time, json_encode($msg));

                //发送IM消息
                $this->sendMessage(array($uid), $gid, $descType, 1);
            }
            unset($groupAdd);
        }
        return true;
    }



    /*
     * 上传群组头像，并生成缩略图
     * @return $array
    */
    public function uploadGroupHeader($inputName, $imgName)
    {
        $header = $sourceImg = '';
        $sourceImg = $this->base->load('qiniu')->uploadQiNiuImg($inputName, $imgName);
        $sourceImg .= '';
        if($sourceImg != '')
        {
            extract($this->base->config['qiniu']);
            $sourceKey = str_replace('http://'.$bucket.'.'.$host, '', $sourceImg);
            $newImgName = 'thumb'.$sourceKey;
            // 生成EncodedEntryURI的值
            $encodedEntryURI=common::urlsafe_base64_encode("$bucket:$newImgName");
            $newurl = $bucket.'.'.$host.$sourceKey.'?imageView2/2/w/180/h/180';
            $newurl .= '|saveas/'.$encodedEntryURI;
            $sign = hash_hmac("sha1", $newurl,$secretKey, true);

            //对签名进行URL安全的Base64编码
            $encodedSign = common::urlsafe_base64_encode($sign);

            //最终得到的完整下载URL
            $data = common::getContents("http://".$newurl."/sign/".$accessKey.":".$encodedSign);
            $data = json_decode($data, true);
            if(isset($data['key']))
            {
                $header = 'http://'.$bucket.'.'.$host . $data['key'];
            }
        }
        return compact('header', 'sourceImg');
    }
    /*
     * 处理群组邀请
     * int $gid
     * int $uid
     * int $agree
     * @return int $status
    */
    public function doInvitation($gid, $uid, $agree)
    {
        $status = $this->db->getOne("select status from r_group_add where gid = '{$gid}' and uid = '$uid'");
        if($status === false)
        {
            return 7;
        }
        else if($status == 4)//处理群主、管理员发出的邀请
        {
            if($agree)//如果同意,加入群组
            {
                $status = $this->joinGroup($gid, $uid) ? 0 : $status;

                //更新消息状态
                $this->updateMessage('3',$gid, array($uid), 'G3');

                //向群主、管理员发送一条待处理通知,
                $groupUserId = $this->getGroupManagers($gid);
                $this->loginfo("doInvitation--------------11111-------".var_export($groupUserId,true));
                $this->sendMessage($groupUserId, $gid,'G4');
            }
            else//如果不同意,更改状态
            {
                $groupAdd = array('gid' => $gid,
                                  'uid' => $uid,
                                  'status' => 5,
                                  'lastupdate' => time(),
                          );
                if($this->db->updateRowTable('r_group_add', $groupAdd))
                {
                    $status = 5;
                }
            }
        }else if($status == 8 ){//处理普通用户发出的邀请
            if($agree)//如果同意,
            {
                $this->updateMessage('3',$gid, array($uid), 'G10',2);
                //向群主、管理员发送一条待处理通知,
                $groupUserId = $this->getGroupManagers($gid);
                $this->sendMessage($groupUserId, $gid,'G1',1);
                
                $groupAdd = array('gid' => $gid,
                                  'uid' => $uid,
                                  'status' => 10,
                                  'lastupdate' => time(),
                          );
                if($this->db->updateRowTable('r_group_add', $groupAdd))
                {
                    $status = 10;
                }
                
            }
            else//如果不同意,更改状态
            {
                $groupAdd = array('gid' => $gid,
                                  'uid' => $uid,
                                  'status' => 9,
                                  'lastupdate' => time(),
                          );
                if($this->db->updateRowTable('r_group_add', $groupAdd))
                {
                    $status = 9;
                }
            }
        }
        return $status;
    }
    /*
     * 获取群主+随机N个群组成员列表
     * int $gid
     * int $limit
     * @return array()
    */
    public function getGroupRandomMem($gid, $limit=7)
    {
        $members = array();
        $groupInfo = $this->getGroupInfo($gid);
        if(empty($groupInfo) || $groupInfo['isDismiss'] == 1)
        {
            return $members;
        }
        $host = $this->redis->hget(REDIS_PREFIX.'GroupHost', $gid);
        $host && $members[] = $host; // 群主放在第一位
        $tmpMem = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, '-inf','+inf');
        if(!empty($tmpMem))
        {
            $tmpMem = array_diff($tmpMem, $members);
            $memNum = count($tmpMem);
            $limit =  $limit - 1;
            if($memNum >= 1)
            {
                $limit > $memNum && $limit = $memNum;
                $tmpKey = array_rand($tmpMem, $limit);
                $selectedMem =array();
                if(!is_array($tmpKey))
                {
                    $selectedMem[] = $tmpMem[$tmpKey];
                }
                else {
                    foreach ($tmpKey as $v) {
                        $selectedMem[] = $tmpMem[$v];
                    }
                }
                $members = array_merge($members, $selectedMem);
            }
        }
        if(!empty($members))
        {
            foreach ($members as & $v) {
                $uid = $v;
                $v = array();
                $v['uid'] = $uid;
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'header');
                unset($uid);
            }
        }
        else{
            $members = array();
        }
        return $members;
    }
    /*
     * 获取群组本日跑步人数及总里程
     * int $gid
     * @return
    */
    public function getTodayRun($gid)
    {
        $mileage = '0';
        $users = '0';
        $result = compact('users', 'mileage');
        if($gid)
        {
            $start = strtotime(date("Y-m-d"));
            $end = $start + 86400;
            $data = $this->db->getRow("select count(distinct(uid)) as users, sum(mileage) as mileage from r_group_run where gid = '{$gid}' and updatetime >= '{$start}' and updatetime < '{$end}' and is_delete = 0");
            if($data)
            {
                $data['mileage'] = round($data['mileage'], 2).'';
                $result = $data;
            }
        }
        return $result;
    }
    /*
     * 获取群组管理员列表
     * int $gid
     * @return
    */
    public function getGroupAdmin($gid)
    {
        $time = $this->base->time;
        $admins = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, '('.$time,$time*2);
        empty($admins) && $admins = array();
        return $admins;
    }
    /*
     * 获取群组群主+管理员列表
     * int $gid
     * @return
    */
    public function getGroupManagers($gid)
    {
        $time = $this->base->time;
        $managers = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, '('.$time, '+inf');

        empty($managers) && $managers = array();
        return $managers;
    }
    /*
     * 群组成员列表 (群主+管理员+普通成员)
     * int $gid
     * @return
    */
    public function getGroupMember($gid)
    {
        $result = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, 0,'+inf');
        if(empty($result))
        {
            $this->createGmemberRedis($gid);
            $result = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, 0,'+inf');
        }
        !$result && $result = array();
        return $result;
    }
    /*
     * 群组普通成员列表
     * int $gid
     * @return
    */
    public function getCililian($gid, $uid = 0, $direc = 'next', $offset = 20)
    {
        $min = 0;
        $max = $this->base->time;
        $limit = array(0, intval($offset));
        $redisKey = REDIS_PREFIX.'GMB_'.$gid;
        if($uid > 0 )
        {
            $point = $direc == 'next' ? $this->redis->ZRANK($redisKey, $uid) : $this->redis->ZREVRANK($redisKey, $uid);
            $direc == 'next' && $point > $max && $point = $max;
            $result = $direc == 'next' ? $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, $point,  $min,array('limit' => $limit)) : $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, $max,$point, array('limit' => $limit));
            !empty($result) && $direc != 'next' && asort($result);
        }
        else
        {
            $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, $max,  $min,array('limit' => $limit));
        }
        if($this->base->vn < 2700) $result = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'GMB_'.$gid, 0,$max);
        !$result && $result = array();
        return $result;
    }
    /*
     * 创建群组成员列表REDIS
     * int $gid
     * @return
    */
    public function createGmemberRedis($gid)
    {
        $this->redis->del(REDIS_PREFIX.'GMB_'.$gid);
        $members = $this->db->getAll("select gid, uid, role, `addtime`, lastupdate from r_gmember where gid = '{$gid}' and role >= 0 and role < 3 order by addtime ASC");
        if($members)
        {
            foreach ($members as $v) {
                !$v['addtime'] && $v['addtime'] == $v['lastupdate'];
                switch ($v['role']) {
                    case '0':
                        $score = $v['addtime'];
                        break;
                    case '1':
                        $score = $v['addtime'] * 3;
                        break;
                    case '2':
                        $score = $v['addtime'] * 2;
                        break;
                    default:
                        break;
                }
                if(isset($score))
                    $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$v['gid'], intval($score), $v['uid']);
            }
        }
        return ;
    }
    /*
     * 设置管理员
     * int $gid
     * array $uids
     * @return
    */
    public function setGroupAdmin($gid, $uids, $isAdmin = FALSE)
    {
        $role = $this->getGroupRole($gid, $this->base->uid);

        if($role != 1 && !$isAdmin)
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
        foreach ($uids as $uid) {
            if($this->getGroupRole($gid, $uid) != 0)
            {
                $_ENV['error']->getErrors(101);
                exit;
            }
        }
        $admins = $this->getGroupAdmin($gid);
        $limit = $this->base->config['group']['adminLimit'] - count($admins);
        if($limit < count($uids))
        {
            $_ENV['error']->getErrors(906);
            exit;
        }
        $role = 2;
        $lastupdate = time();
        $groupName = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$gid, 'name');
        $notice = sprintf("您已被群主设置为 %s 管理员", $groupName);
        foreach ($uids as $uid) {
            $this->db->updateRowTable('r_gmember', compact('gid','uid','role','lastupdate'));
            $score = $this->redis->ZSCORE(REDIS_PREFIX.'GMB_'.$gid, $uid);
            if(!$score)
            {
                $score = $this->db->getOne("select addtime from r_gmember where gid = '{$gid}' and uid = '{$uid}'");
            }
            $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, $score * 2, $uid);
            // $this->redis->ZADD(REDIS_PREFIX.'GroupAdmin_'.$gid, $lastupdate, $uid);
            $this->redis->ZADD(REDIS_PREFIX.'MGListBR_'.$uid, $lastupdate + 1000000000, $gid);
            $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $uid, $role);
            // 向成员发通知

            $clientInfo = $this->base->load('client')->getClientInfoByUid($uid);
            if(isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
                $this->redis->ZADD(REDIS_PREFIX.'QuitGNotice_'.$uid, $lastupdate, $notice);
            }
            //发送IM消息
            $this->sendMessage(array($uid), $gid,'G8');
        }
        return 1;
    }
    /*
     * 取消管理员
     * int $gid
     * int $uid
     * @return
    */
    public function cancelGroupAdmin($gid, $uid, $isAdmin = FALSE)
    {
        $result = 0;
        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            $_ENV['error']->getErrors(905);
            exit;
        }
        $managerRole = $this->getGroupRole($gid, $this->base->uid);
        if($managerRole != 1 && !$isAdmin)
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
        if($this->getGroupRole($gid, $uid) != 2)
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $role = 0;
        $lastupdate = $this->base->time;
        if($this->db->updateRowTable('r_gmember', compact('gid','uid','role','lastupdate')))
        {
            // 修改用户在群组成员列表中的score值
            $score = $this->redis->ZSCORE(REDIS_PREFIX.'GMB_'.$gid, $uid);
            if(!$score || $score < $lastupdate)
            {
                $score = $this->db->getOne("select addtime from r_gmember where gid = '{$gid}' and uid = '{$uid}'");
                $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, $score * 2, $uid);
            }
            else
                $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, intval($score/2), $uid);
            $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $uid, $role);
            $this->redis->ZADD(REDIS_PREFIX.'MGListBR_'.$uid, $lastupdate, $gid);
            

            $clientInfo = $this->base->load('client')->getClientInfoByUid($uid);
            if(isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
                // 向成员发通知
                $notice = sprintf("您已被群主取消 %s 的管理员权限", $gInfo['name']);
                $this->redis->ZADD(REDIS_PREFIX.'QuitGNotice_'.$uid, $lastupdate, $notice);
            }
            //发送IM消息
            $this->sendMessage(array($uid), $gid,'G9');

            $result = 1;
        }
       return $result;
    }
    /*
     * 申请加入群组
     * int $gid
     * int $uid
     * @return
    */
    public function applyForGroup($gid, $uid ,$reason)
    {
        if(empty($gid) || empty($uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $role = $this->getGroupRole($gid, $uid);
        if($role == -1 || $role == 3)
        {
            $status = 7;
            $time = time();
            $groupAdd = array('gid' => $gid,
                              'manager'     => 0,
                              'uid'         => $uid,
                              'status'      => 1,
                              'addtime'     => $time,
                              'lastupdate'  => $time ,
                              'reason'      => $reason,
                              'isShow'      => 1
                );
            if($role == 3) unset($groupAdd['addtime']);
            $gInfo = $this->getGroupInfo($gid);
            if(isset($gInfo['isverify']) && $gInfo['isverify'] == 1){
                $groupAdd['status'] = 0;
                $this->sendMessage(array($uid),$gid,'G12',0);
            }
            $rid = $this->db->insertRowTable('r_group_add', $groupAdd);
            if($rid)
            {
                $status = 1;
                if(isset($gInfo['isverify']) && $gInfo['isverify'] == 1){
                    $status = 0;
                    if($this->base->vn < 2700 && $this->base->projectId == 1) $status = 1;
                    $this->joinGroup($gid, $uid);
                }else{
                    // 向群主发通知
                    $GroupHost = $this->redis->hget(REDIS_PREFIX.'GroupHost', $gid);

                    $this->redis->ZADD(REDIS_PREFIX.'GA_'.$gid.'_'.$GroupHost, $time, $rid);
                    $admins = $this->getGroupAdmin($gid);
                    if(!empty($admins))
                    {
                        foreach ($admins as $key => $admin) {
                            $clientInfo = $this->base->load('client')->getClientInfoByUid($admin);
                            if(isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
                                $this->redis->ZADD(REDIS_PREFIX.'GA_'.$gid.'_'.$admin, $time, $rid);
                            }
                        }
                    }

                    //根据gid去r_gmember表中获取管理员信息
                    $groupUsers = $this->getGroupManagers($gid);
                    $this->sendMessage($groupUsers, $gid,'G1',1,0,$reason);
                }


            }
            return $status;
        }
        else
        {
            $status = $this->db->getOne("select status from r_group_add where gid = '{$gid}' and uid = '{$uid}'");
            return $status;
        }
    }
    /*
     * 群组管理消息总数
     * int $gid
     * int $uid
     * @return
    */
    public function GApplyNum($gid, $uid)
    {
        if(empty($gid) || empty($uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            $_ENV['error']->getErrors(905);
            exit;
        }
        $role = $this->getGroupRole($gid, $uid);
        if($role == 1 || $role == 2)
        {
            $num = $this->redis->ZCARD(REDIS_PREFIX.'GA_'.$gid.'_'.$uid);
            return intval($num);
        }
        else
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
    }
    /*
     * 群组管理消息列表
     * int $gid
     * int $uid
     * @return
    */
    public function GApplyList($gid, $uid,$point, $direc ='next', $offset=20)
    {
        if(empty($gid) || empty($uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            $_ENV['error']->getErrors(905);
            exit;
        }
        $role = $this->getGroupRole($gid, $uid);
        if($role == 1 || $role == 2)
        {
            $host = $this->redis->hget(REDIS_PREFIX.'GroupHost', $gid);
            $this->redis->del(REDIS_PREFIX.'GA_'.$gid.'_'.$uid);
            if($point > 0)
            {
                $sql = "select id, lastupdate as `order`,uid,status from r_group_add where gid ='{$gid}' and status < 4 and uid != '{$host}' and isShow = 1";
                if($direc == 'next')
                {
                    $sql .= " and lastupdate < $point order by lastupdate DESC";
                }
                else
                {
                    $sql .= " and lastupdate > $point order by lastupdate ASC";
                }
                $sql .= " limit {$offset}";
            }
            else
            {
                $sql = "select id, lastupdate as `order`,uid,status from r_group_add where gid ='{$gid}' and status < 4 and uid != '{$host}' and isShow = 1 order by lastupdate DESC limit {$offset}";
            }
            $result = $this->db->getAll($sql);
            if(!empty($result))
            {
                foreach ($result as & $v) {
                    $v['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'nickname');
                    $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'header');
                }
                if($point > 0 && direc != 'next')
                {
                    rsort($result);
                }
            }
            else
                $result = array();
            return $result;

        }
        else
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
    }
    /*
     * 群组邀请消息概况
     * int $uid
     * @return
    */
    public function dealGroupApply($gid, $uid, $id, $dotype)
    {
        $status = $this->db->getOne("select status from r_group_add where gid = '{$gid}' and id = '{$id}' and (status < 4 or status = 10) and isShow = 1");
        if($status === false)
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $data = array('id' => $id,
                      'manager' => $uid,
                      'lastupdate' => time(),
                        );
        switch ($dotype) {
            case '0':
                if($status == 1) // 拒绝申请
                {
                    $data['status'] = 2;
                    if($this->db->updateRowTable('r_group_add', $data))
                    {
                        $status = 2;
                    }
                }
                break;
            case '1':
                if($status == 1 || $status == 10) // 通过申请IM (状态为10表明是管理员同意普通成员邀请的用户)
                {
                    $data['status'] = 0;
                    $user = $this->db->getOne("select uid from r_group_add where id = '{$id}'");
                    if($this->joinGroup($gid, $user, $uid))
                    {
                        //$status = 0;
                        //
                        $manager = $this->db->getOne("select uid from r_group_add where id = '{$id}'");

                        $gMemberIds = $this->getGroupManagers($gid);

                        if($status == 1){ //如果status为1,就给申请者发送消息;
                            //$manager = $this->db->getOne("select uid from r_group_add where id = '{$id}'");

                            //更新消息状态
                            $this->updateMessage('3',$gid, $gMemberIds, 'G1');
                            $this->updateMessage('3',$gid, $gMemberIds, 'G11');

                            //发送IM消息
                            $this->sendMessage(array($manager), $gid,'G2');
                        }

                        if($status == 10 ){//如果消息状态为10就给发起邀请的普通成员发送消息

                            $invite_id = $this->db->getOne("select invite_id from r_group_add where id = '{$id}'");
                            //更新邀请人同意后提交申请的消息状态
                            $this->updateMessage('3',$gid, $gMemberIds, 'G1');

                            //更新邀请的消息状态
                            $this->updateMessage('3',$gid, array($manager), 'G10');
                            //发送IM消息
                            $this->sendMessage(array($invite_id), $gid,'G4');
                        }
                        
                        $status = 0;
                    }
                }
                break;
            case '2':
                $data['isShow'] = 0; // 删除消息
                $this->db->updateRowTable('r_group_add', $data);
                break;
            default:
                # code...
                break;
        }
        return $status;
    }

    /*
     * 记录日志
     * @param  [type] $fileName [description]
     * @param  [type] $content  [description]
     * @return [type]           [description]
     */
    private function loginfo($content, $fileName = 'log', $folder = 'group'){
        //文件所处目录
        $path = $this->base->config['log-dir'] . $folder . "/";
        //查看文件目录是否存在,不存在创建
        !file_exists($path) && mkdir($path);
        //文件名称及类型
        $logName = $fileName.'.txt';
        //写入方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。
        $fp = fopen($path.$logName, "a");
        //文件内容前缀
        $log_prefix = '---start---'.date('Y-m-d H:i:s')."---\n";
        //文件内容后缀
        $log_suffix = '---end---'.date('Y-m-d H:i:s')."---\n";
        //写入内容
        fwrite($fp, $log_prefix . $content . "\n" . $log_suffix);
        //写入换行
        fwrite($fp, "\n");
        //关闭
        fclose($fp);
    }

    /*
     * 群组邀请消息概况
     * int $uid
     * @return
    */
    public function GInviteView($uid)
    {
        $redisKey = REDIS_PREFIX.'GInvite_'.$uid;
        $num = $this->redis->ZCARD($redisKey);
        $num = intval($num);
        $data = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf','-inf',array(array('limit' => array(0, 1))));
        $msg = '';
        $header = '';
        if(!empty($data) && common::is_json($data[0]))
        {
            $v = json_decode($data[0], true);
            if(isset($v['uid']) && isset($v['gid']))
            {
                $header = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'header');
                $nickname = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'nickname');
                $gName = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$v['gid'], 'name');
                $msg = sprintf("%s邀请你加入%s", $nickname, $gName);
            }
        }
        return compact('num','msg','header');
    }
    /*
     * 群组解散、被踢出群组及被设为管理员的消息通知
     * int $uid
     * @return
    */
    public function getQuitNotice($uid)
    {
        $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'QuitGNotice_'.$uid,'+inf','-inf');
        empty($result) && $result = array();
        $this->redis->del(REDIS_PREFIX.'QuitGNotice_'.$uid);
        return $result;
    }
    /*
     * 群组邀请列表
     * int $uid
     * @return
    */
    public function invitationList($uid)
    {
        $time = strtotime("-1 months");
        $result = $this->db->getAll("select gid, manager from r_group_add where uid = '{$uid}' and status = '4' and addtime > '{$time}' and isShow = 1 order by addtime DESC");
        if(!empty($result))
        {
            foreach ($result as & $v) {
                $v['inviter'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['manager'],'nickname');
                $v['name'] = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$v['gid'],'name');
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$v['gid'],'header');
            }
        }
        else
            $result = array();
        $this->redis->del(REDIS_PREFIX.'GInvite_'.$uid);
        return $result;
    }
    /*
     * 我的群组列表
     * int $uid
     * @return
    */
    public function myGroupList($uid, $withInfo = true)
    {
        $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'MGList_'.$uid, '+inf', '-inf');
        if(empty($result))
        {
            $data = $this->db->getAll("select gid, lastupdate from r_gmember where uid = '{$uid}' and role >=0 && role < 3 order by lastupdate DESC");
            $result =array();
            if(!empty($data))
            {
                foreach ($data as $v) {
                    $gInfo = $this->getGroupInfo($v['gid']);
                    if($gInfo && $gInfo['isDismiss'] == 0)
                    {
                        $this->redis->ZADD(REDIS_PREFIX.'MGList_'.$uid, $v['lastupdate'], $v['gid']);
                        $result[] = $v['gid'];
                    }
                }
            }
        }
        if(!empty($result))
        {
            if($withInfo == true)
            {
                foreach ($result as & $v) {
                    $gid = $v;
                    $gInfo = $this->getGroupInfo($gid);
                    if($gInfo)
                    {
                        $v = array('gid'    => $gid,
                               'name'   => $gInfo['name'],
                               'header' => $gInfo['header'],
                               'slogan' => $gInfo['slogan'],
                               'role' => $this->getGroupRole($gid, $uid)
                        );
                    }
                    else
                    {
                        unset($v);
                        $this->redis->ZREM(REDIS_PREFIX.'MGList_'.$uid, $v);
                    }
                }
            }
        }
        else
            $result = array();
        return $result;
    }
    /*
     * 我的群组列表(按照用户在群组中的身份分类)
     * int $uid
     * int $type 在群组中的身份 0:普通成员  1：群主   2：管理员  3：管理员+普通成员
     * @return
    */
    public function myGroupListByRole($uid, $type = 1)
    {
        $redisKey = REDIS_PREFIX.'MGListBR_'.$uid;

        if(!$this->redis->exists($redisKey))
        {
            $this->createMyGroupByRole($uid);
        }
        $result = array();
        switch ($type) {
            case 0:
                $groupList = $this->redis->ZREVRANGEBYSCORE($redisKey, 2000000000, 0);
                break;
            case 1:
                $groupList = $this->redis->ZREVRANGEBYSCORE($redisKey, 5000000000, 4000000000);
                break;
            case 2:
                $groupList = $this->redis->ZREVRANGEBYSCORE($redisKey, 3000000000, 2000000000);
                break;
            case 3:
                $groupList = $this->redis->ZREVRANGEBYSCORE($redisKey, 3000000000, 0);
                break;
            default:
                # code...
                break;
        }
        if(!empty($groupList))
        {
            foreach ($groupList as $v) {
                $gid = $v;
                $gInfo = $this->getGroupInfo($gid);
                if($gInfo && $gInfo['isDismiss'] == 0)
                {
                    $act = $this->base->load('groupActivity')->getIngAct($gid,0,5);
                    $result[] = array('gid'    => $gid,
                           'name'   => $gInfo['name'],
                           'header' => $gInfo['header'],
                           'slogan' => $gInfo['slogan'],
                           'role' => $this->getGroupRole($gid, $uid),
                           'isActivity' => empty($act) ? 0 : 1,
                           'totalMileage' => floatval($this->getTotalMileageByGid($gid)),
                           'num' => $gInfo['members'],
                           'authenticate'=> $this->isAuth($gid)
                    );
                }
                else
                {
                    $this->redis->ZREM($redisKey, $gid);
                }
            }
        }
        else
            $result = array();
        return $result;
    }
    /*
     * 解散群组
     * @return
    */
    public function dismissGroup($gid, $uid)
    {
        if(empty($gid) || empty($uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            $_ENV['error']->getErrors(905);
            exit;
        }
        if($this->getGroupRole($gid, $uid) != 1)
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
        if($this->db->update("update r_group set isDismiss = 1 where gid = '{$gid}'"))
        {
            $this->base->load('xunSearch')->init('group')->delIndex($gid,"gid");
            $this->redis->hset(REDIS_PREFIX.'GroupInfo_'.$gid, 'isDismiss', "1");
            $this->redis->HINCRBY(REDIS_PREFIX.'GroupCreateNum', $uid, -1); // 用户创建群组数-1
            $this->redis->zrem(REDIS_PREFIX."groupMileage",$gid);
            $key = $this->getCityKey($gInfo['province'],$gInfo['city']);
            !empty($key) && $this->redis->srem($key,$gid);
            $this->db->update("update r_group_add set isShow = 0 where gid = '{$gid}'");
            //去除推荐列表
            if($this->base->load('admin')->remRecommendGroup($gid))
            {
                $this->redis->ZREM(REDIS_PREFIX.'RecGroupList', $gid);
            }
            //移除认证列表
            $this->db->query("delete from r_group_auth where gid=$gid");
            $members = $this->getGroupMember($gid);
            if(!empty($members))
            {
                $nickname = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'nickname');
                $dismissmsg = sprintf("群主%s已经将 %s 群组解散", $nickname, $gInfo['name']);
                $time = time();
                foreach ($members as $v) {
                    
                    // 从用户所在的群组列表中移除
                    $this->redis->ZREM(REDIS_PREFIX.'MGList_'.$v, $gid); // 我的群组列表
                    $this->redis->ZREM(REDIS_PREFIX.'MGListBR_'.$v, $gid); // 我的群组列表
                    $this->redis->ZREM(REDIS_PREFIX."MGRankList_".$v,$gid);
                    
                    $clientInfo = $this->base->load('client')->getClientInfoByUid($v);
                    if(isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
                        // 向成员发通知
                        $this->redis->ZADD(REDIS_PREFIX.'QuitGNotice_'.$v, $time, $dismissmsg);
                    }

                    //根据gid去r_gmember表中获取所有成员信息
                    $rst = $this->getGroupRole($gid,$v);
                    if(1 != $rst){
                        $this->sendMessage(array($v), $gid,'G7');
                    }

                    //解散IM群组
                    $this->base->load('message')->groupDismiss($uid, $gid);
                    
                }
            }
            //善后
            $this->redis->lpush(REDIS_PREFIX.'GroupDismiss',$gid);
        }
        else
        {
            return false;
        }
        return 1;
    }
    /*
     * 删除成员
     * int $gid
     * int $manager  群组管理者ID
     * int $uid  被删除用户ID
     * @return
    */
    public function delMember($gid, $manager, $uid, $admin=false)
    {
        if(empty($gid) || empty($uid) || empty($manager))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $mrole = $this->getGroupRole($gid, $manager);
        if(!$admin && !in_array($mrole, array(1,2)))
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
        $role = $this->getGroupRole($gid, $uid);
        if($role < 0 || $role > 2)
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if(!$admin && $mrole == $role)
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
        $time = time();
        $groupAdd = array('gid' => $gid,
                          'uid' => $uid,
                          'manager' => $manager,
                          'status' => 6,
                          'lastupdate' => $time,
                          );
        if($this->db->updateRowTable('r_group_add', $groupAdd))
        {
            $groupMem = array('gid' => $gid,
                          'uid' => $uid,
                          'role' => 3,
                          'lastupdate' => time(),
                    );
            $result = $this->db->updateRowTable('r_gmember', $groupMem) != false ? true : false;
            if($result)
            {
                $this->db->update("update r_group set members = members-1 where gid = '{$gid}'");
                $this->redis->ZREM(REDIS_PREFIX.'GMB_'.$gid,$uid); //群成员列表
                $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $uid, 3); //群成员身份标识
                $this->redis->HINCRBY(REDIS_PREFIX.'GroupInfo_'.$gid, 'members', -1);
                $this->redis->ZREM(REDIS_PREFIX.'MGList_'.$uid, $gid); // 我的群组列表
                $this->redis->ZREM(REDIS_PREFIX.'MGListBR_'.$uid, $gid); // 我的群组列表
                // 消息
                if(!$admin){
                    $userName = $mrole == 1 ? '群主' : '管理员';
                    $userName .= $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$manager, 'nickname');
                    $groupName = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$gid, 'name');

                    $clientInfo = $this->base->load('client')->getClientInfoByUid($uid);
                    if(isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
                        $msg = sprintf("您已被%s移除群组 %s", $userName, $groupName);
                        $this->redis->ZADD(REDIS_PREFIX.'QuitGNotice_'.$uid,$time, $msg);
                    }
                }
                
                //向被移除的成员发生通知消息
                $this->sendMessage(array($uid),$gid,'G6');

                //退出IM群组
                $this->base->load('message')->groupQuit($uid, $gid);
            }
        }
        return $result != false ? 1 : 0;
    }
    /*
     * 退出群组
     * int $gid
     * int $uid 用户ID
     * @return
    */
    public function quitGroup($gid, $uid)
    {
        if(empty($gid) || empty($uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            $_ENV['error']->getErrors(905);
            exit;
        }
        $role = $this->getGroupRole($gid, $uid);
        if($role == 1)
        {
            $_ENV['error']->getErrors(907);
            exit;
        }
        else if($role != 2 && $role != 0)
        {
            $_ENV['error']->getErrors(903);
            exit;
        }
        $time = time();
        $groupAdd = array('gid' => $gid,
                          'uid' => $uid,
                          'manager' => 0,
                          'status' => 3,
                          'lastupdate' => $time,
                    );
        if($this->db->updateRowTable('r_group_add', $groupAdd))
        {
            $groupMem = array('gid' => $gid,
                          'uid' => $uid,
                          'role' => 3,
                          'lastupdate' => time(),
                    );
            $result = $this->db->updateRowTable('r_gmember', $groupMem) != false ? true : false;
            if($result)
            {
                $rid = $this->db->getOne("select id from r_group_add where gid = '{$gid}' and uid = '{$uid}'");
                $this->db->update("update r_group set members = members-1 where gid = '{$gid}'");
                $this->redis->ZREM(REDIS_PREFIX.'GMB_'.$gid,$uid); //群成员列表
                $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $uid, 3); //群成员身份标识
                $this->redis->HINCRBY(REDIS_PREFIX.'GroupInfo_'.$gid, 'members', -1);
                $this->redis->ZREM(REDIS_PREFIX.'MGList_'.$uid, $gid); // 我的群组列表
                $this->redis->ZREM(REDIS_PREFIX.'MGListBR_'.$uid, $gid); // 我的群组列表
                $this->redis->ZREM(REDIS_PREFIX."MGRankList_".$uid,$gid); //我的群组排行
                // 发消息通知
                $GroupHost = $this->redis->hget(REDIS_PREFIX.'GroupHost', $gid);
                

                $this->redis->ZADD(REDIS_PREFIX.'GA_'.$gid.'_'.$GroupHost, $time, $rid);
                $admins = $this->getGroupAdmin($gid);
                if(!empty($admins))
                {
                    foreach ($admins as $key => $admin) {
                        $clientInfo = $this->base->load('client')->getClientInfoByUid($admin);
                        if(isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
                            $this->redis->ZADD(REDIS_PREFIX.'GA_'.$gid.'_'.$admin, $time, $rid);
                        }
                    }
                }

                //根据gid去r_gmember表中获取管理员信息
                $groupUsers = $this->getGroupManagers($gid);
                $this->sendMessage($groupUsers, $gid,'G5');

                //退出IM群组
                $this->base->load('message')->groupQuit($uid, $gid);
            }
        }
        return $result != false ? 1 : 0;
    }

    /**
     * 退出IM消息群
     * @param  [type] $uid [description]
     * @param  [type] $gid [description]
     * @return [type]      [description]
     */
    // private function quitImGroupNotice($uid,$gid){

    //     $groupInfo = $this->db->getRowTable('r_group', array('name'), "gid={$gid}");

    //     $fromUserId = 10023;//群消息账户
    //     $toUserId = $uid;
    //     $objectName = 'RC:TxtMsg';//文本
    //     $content = '{"content":"你被邀请加入"'.$groupInfo['name'].'"群,去查看!","extra":"helloExtra"}';//
    //     $pushContent = '你被邀请加入某某群,去查看!';//
    //     $pushData = '你被邀请加入某某群,去查看!';//

    //     $this->base->load('message')->messageSystemPublish($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
    // }

    /*
     * 获取用户月跑步里程
     * int $gid
     * string $date 月份（年-月） or 周数
     * @return
    */
    /*
    public function getUserRunTotal($gid, $uid, $date='')
    {
        empty($date) && $date = date("Y-m");
        $result = $this->redis->ZSCORE(REDIS_PREFIX.'GMRank_'.$gid.'_'.$date, $uid);
        if($result === false)
        {
            if(strpos($date, '-') !== false)
            {
                $start = strtotime($date);
                $end = strtotime("$date +1 month") -1;
            }
            else
            {
                $date = substr_replace($date, substr($date, 0, 4).'W',0, 4);
                $start = strtotime($date);
                $end = $start + 7*86400 -1;
            }
            $result = $this->db->getOne("select sum(mileage) from r_group_run where gid = '{$gid}' and uid = '{$uid}' and updatetime >= '{$start}' and updatetime < '{$end}' and is_delete = 0");
            if($result)
            {
                $result = round($result, 2);
                $this->redis->ZADD(REDIS_PREFIX.'GMRank_'.$gid.'_'.$date, $result, $uid);
            }
        }
        return $result;
    }
    */
    /*
     * 获取群组月跑步总里程
     * int $gid
     * string $date 月份（年-月）/ 周数（年周）
     * @return
    */
    public function getGroupRunMoWTotal($gid, $date)
    {
        $result = $this->redis->hget(REDIS_PREFIX.'GRTotal'.$date, $gid);
        if($result === false)
        {
            if(stripos($date, '-') !== false)
            {
                $start = strtotime($date);
                $end = strtotime("$date +1 month") -1;
            }
            else
            {
                $date = substr_replace($date, substr($date, 0, 4).'W',0, 4);
                $start = strtotime($date);
                $end = $start + 7*86400 -1;
            }
            $result = $this->db->getOne("select sum(mileage) from r_group_run where gid = '{$gid}' and updatetime >= '{$start}' and updatetime < '{$end}' and is_delete = 0");
            if($result)
            {
                $result = round($result, 2);
                $this->redis->hset(REDIS_PREFIX.'GRTotal'.$date, $gid, $result);
            }
        }
        $result = round($result, 2);
        return $result;
    }
    /*
     * 获取群组跑步总里程
     * int $gid
     * @return
    */
    /*
    public function getGroupRunTotal($gid)
    {
        $result = $this->redis->hget(REDIS_PREFIX.'GRTotal', $gid);
        if($result === false)
        {
            $result = $this->db->getOne("select sum(mileage) from r_group_run where gid = '{$gid}' and is_delete = 0");
            if($result)
            {
                $result = round($result, 2);
                $this->redis->hset(REDIS_PREFIX.'GRTotal', $gid, $result);
            }
        }
        $result = round($result, 2);
        return $result;
    }
    */
    /*
     * 获取群组月目标
     * int $gid
     * string $month 月份（年-月）
     * @return
    */
    public function getGroupTarget($gid, $month='')
    {
        empty($month) && $month = date("Y-m");
        $result = $this->redis->hget(REDIS_PREFIX.'GT'.$month, $gid);
        if($result === false)
        {
            $result = $this->db->getOne("select target from r_group_target where gid = '{$gid}' and month = '{$month}'");
            if($result)
            {
                $this->redis->hset(REDIS_PREFIX.'GT'.$month, $gid, $result);
            }
        }
        return $result;
    }
    /*
     * 获取用户在群组中月目标
     * int $gid
     * int $uid
     * string $month 月份（年-月）
     * @return
    */
    public function getUserTarget($gid, $uid, $month='')
    {
        empty($month) && $month = date("Y-m");
        $result = $this->redis->hget(REDIS_PREFIX.'UT'.$month.'_'.$gid, $uid);
        if($result === false)
        {
            $result = $this->db->getOne("select target from r_user_target where gid = '{$gid}' and uid = '{$uid}' and month = '{$month}'");
            if($result)
            {
                $this->redis->hset(REDIS_PREFIX.'UT'.$month.'_'.$gid, $uid, $result);
            }
        }
        return $result;
    }
    /*
     * 获取群组用户月目标总和
     * int $gid
     * string $month 月份（年-月）
     * @return
    */
    public function getGroupTotalTarget($gid, $month='')
    {
        $result = 0;
        empty($month) && $month = date("Y-m");
        $targets = $this->redis->HVALS(REDIS_PREFIX.'UT'.$month.'_'.$gid);
        if($targets)
        {
            $result = array_sum($targets);
            $result = round($result, 2);
        }
        return $result;
    }
    /*
     * 设置群组目标
     * int $gid
     * int $uid
     * float $target 目标
     * @return
    */
    public function setGroupTarget($gid, $uid, $target)
    {
        $result = false;
        if($target <= 0)
        {
            return $result;
        }
        $target = round($target, 2);
        $month = date("Y-m");
        $limit = $this->base->config['group']['targetModL'];
        $modTimes = $this->redis->hget(REDIS_PREFIX.'GTMT'.$month, $gid);
        if($modTimes >= $limit)
        {
            $_ENV['error']->getErrors(908);
            exit;
        }
        $time = time();
        $isFirst = $this->getGroupTarget($gid, $month) === false ? 1 : 0;
        $groupTarget = array('gid'  => $gid,
                             'month'=> $month,
                             'target'=> $target,
                             'uid'  => $uid,
                             'lastupdate'  => $time,
                        );
        $isFirst == 1 && $groupTarget['addtime'] = $time;
        if($this->db->updateRowTable('r_group_target', $groupTarget))
        {
            $this->redis->hset(REDIS_PREFIX.'GT'.$month, $gid, $target);
            $isFirst != 1 && $this->redis->HINCRBY(REDIS_PREFIX.'GTMT'.$month, $gid, 1);
            $result = true;
        }
        return $result;
    }
    /*
     * 设置个人群组中月目标
     * int $gid
     * int $uid
     * float $target 目标
     * @return
    */
    public function setUserTarget($gid, $uid, $target)
    {
        $result = false;
        if($target <= 0)
        {
            return $result;
        }
        $target = round($target, 2);
        $month = date("Y-m");
        $modTimes = $this->redis->hget(REDIS_PREFIX.'GTMT'.$month, $gid);
        if($this->getUserTarget($gid,$uid, $month) !== false)
        {
            return $result;
        }
        $time = time();
        $groupTarget = array('gid'  => $gid,
                             'month'=> $month,
                             'target'=> $target,
                             'uid'  => $uid,
                             'addtime'  => time(),
                        );
        $rel = $this->db->updateRowTable('r_user_target', $groupTarget);
        if($rel)
        {
            $this->redis->hset(REDIS_PREFIX.'UT'.$month.'_'.$gid, $uid, $target); // 个人目标
            $userMileage = $this->redis->ZSCORE(REDIS_PREFIX.'GMRank_'.$gid.'_'.$month,$uid);
            // 群组目标排行榜
            $this->redis->ZADD(REDIS_PREFIX.'GTRank_'.$gid.'_'.$month, round($userMileage/$target, 3), $uid);
            $result = true;
        }
        return $result;
    }
    /*
     * 获取群组目标及个人目标信息
     * int $gid
     * int $uid
     * @return
    */
    public function getTargetInfo($gid,$month=0, $uid)
    {
        (empty($month) || strpos($month, '-') == false) && $month = date("Y-m");

        // 获取用户在群组中角色
        $role = $this->getGroupRole($gid, $uid);

        $GTModifyLimit = $this->base->config['group']['targetModL'];
        $GTModifyTimes = $this->redis->hget(REDIS_PREFIX.'GTMT'.$month, $gid);
        $GTModifyTimes = intval($GTModifyTimes);

        $GTarget = $this->getGroupTarget($gid, $month);
        empty($GTarget) && $GTarget = 0;

        $GRate = $GTarget == 0 ? '0.00' : round($this->getGroupRunMoWTotal($gid,$month)/$GTarget, 3);
        $UTarget = $this->getUserTarget($gid, $uid, $month);
        empty($UTarget) && $UTarget = 0;

        $URate = $UTarget == 0 ? '0.00' : round($this->getUserRunTotal($gid, $uid, 'month', strtotime($month))/$UTarget, 3);
        $allTarget = round($this->getGroupTotalTarget($gid, $month), 2);
        
        return compact('gid','role','GTModifyLimit','GTModifyTimes','GTarget','GRate','UTarget','URate','allTarget');
    }
    /*
     * 群组最佳记录
     * int $gid
     * @return
    */
    public function getBestRecord($gid, $format = true)
    {
        $records = array();
        $recordArr = array('farthest' => '最远跑步纪录',
                           'longest' => '最久跑步纪录',
                           'bestFive' => '5公里最佳纪录',
                           'bestTen' => '10公里最佳纪录',
                           'bestHalf' => '半马最佳纪录',
                           'bestMara' => '全马最佳纪录',
                           'maxTimes' => '跑步次数纪录'
                        );
        foreach ($recordArr as $k => $v) {
            $tmp = $this->redis->hget(REDIS_PREFIX.'GRecord_'.$gid, $k);
            if(empty($tmp))
            {
                $tmp = $this->createRecord($gid, $k);
            }
            if(!empty($tmp))
            {
                $data = @json_decode($tmp, true);
                if(!is_array($data))
                {
                    continue;
                }
                $data['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$data['uid'], 'nickname');
                $data['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$data['uid'], 'header');
                $data['record'] = $v;
                $data['date'] = isset($data['updatetime']) ? date("Y-m-d",$data['updatetime'] ) : '某年某月';
                if(isset($data['updatetime']))
                    unset($data['updatetime']);
                if($format)
                {
                    if($k == 'farthest')
                    {
                        $data['value'] = $data['value'].'km';
                    }
                    else if($k != 'maxTimes')
                    {
                        $data['value'] = common::sec2format($data['value']);
                    }
                    $records[] = $data;
                }
                else
                {
                    $records[$k] = $data;
                }
            }
            unset($tmp, $data);
        }
        empty($records) && $records = array(0);
        return $records;
    }
    /*
     * 生成群组最佳记录
     * int $gid
     * @return
    */
    public function createRecord($gid, $record)
    {
        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            return false;
        }
        $recordArr = array('farthest' => '最远跑步纪录',
                           'longest' => '最久跑步纪录',
                           'bestFive' => '5公里最佳纪录',
                           'bestTen' => '10公里最佳纪录',
                           'bestHalf' => '半马最佳纪录',
                           'bestMara' => '全马最佳纪录',
                           'maxTimes' => '跑步次数纪录'
                        );
        if(!isset($recordArr[$record]))
        {
            return false;
        }
        $data = array();
        switch ($record) {
            case 'farthest':
                $max = $this->db->getRow("select uid, mileage as value, updatetime from r_group_run where gid = '{$gid}' and is_delete =0 order by value DESC limit 1");
                break;
            case 'longest':
                $max = $this->db->getRow("select uid, elapsedtime as value, updatetime from r_group_run where gid = '{$gid}' and is_delete =0 order by value DESC limit 1");
                break;
            case 'bestFive':
                $max = $this->db->getRow("select uid, five_time as value, updatetime from r_group_run where gid = '{$gid}' and is_delete =0 and five_time > 0 order by value ASC limit 1");
                break;
            case 'bestTen':
                $max = $this->db->getRow("select uid, ten_time as value, updatetime from r_group_run where gid = '{$gid}' and is_delete =0 and ten_time > 0 order by value ASC limit 1");
                break;
            case 'bestHalf':
                $max = $this->db->getRow("select uid, half_mtime as value, updatetime from r_group_run where gid = '{$gid}' and is_delete =0 and half_mtime > 0 order by value ASC limit 1");
                break;
            case 'bestMara':
                $max = $this->db->getRow("select uid, mara_time as value, updatetime from r_group_run where gid = '{$gid}' and is_delete =0 and mara_time > 0 order by value ASC limit 1");
                break;
            case 'maxTimes':
                $max = $max = $this->db->getRow("select uid, count(*) as value,updatetime from r_group_run where gid = '{$gid}' and is_delete =0 group by uid order by value DESC limit 1");
                break;
            default:
                return false;
                break;
        }
         $this->redis->del(REDIS_PREFIX.'GRecord_'.$gid, $record);
        if($max)
        {
            $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, $record, json_encode($max));
        }
        return json_encode($max);
    }
    /*
     * 获取群组某日跑步记录信息
     * @return
    */
    public function getGroupRunRecord($gid, $date='')
    {
        empty($date) && $date = date("Y-m-d");
        $start = strtotime($date);
        $end = strtotime("$date +1 day")-1;
        $record = $this->db->getAll("select did, uid, city,mileage,updatetime from r_group_run where gid ='{$gid}' and updatetime >= '{$start}' and updatetime < '{$end}' and is_delete='0' order by updatetime DESC");
        $users = array();  // 跑步的用户ID数组
        $totalMileage = 0; // 总里程
        $lastUser = 0;  // 最后跑步的用户ID
        if(!empty($record))
        {
            foreach ($record as & $v) {
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'], 'header');
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'], 'nickname');
                $v['likes'] = $this->base->load('run')->getRunRecordLikes($v['did'], $gid);
                $v['isLike'] = $this->redis->ZSCORE(REDIS_PREFIX.'RunLike_'.$gid.'_'.$v['did'], $v['uid']) ? 1 : 0;
                empty($users) && $lastUser = $v['uid'];
                $users[] = $v['uid'];
                $totalMileage += $v['mileage'];
            }
        }
        else
            $record = array();
        $users = array_unique($users);
        $totalUser = count($users);
        $message = sprintf("今日本群有%s人跑步，累计里程%skm", $totalUser, $totalMileage);
        $lastHeader  = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$lastUser, 'header');
        return compact('date', 'message','totalUser','totalMileage','lastHeader', 'record');
    }
    /*
     * 获取群组某月有用户跑步的日期
     * @return
    */
    public function getGroupRunCalendar($gid, $month='')
    {
        empty($month) && $month = date("Y-m");
        $start = strtotime($month);
        $end = strtotime("$month +1 month")-1;
        $daysTmp = $this->db->getCol("select updatetime from r_group_run where gid ='{$gid}' and updatetime >= '{$start}' and updatetime < '{$end}' and is_delete='0' order by updatetime ASC");
        $days = array();
        if(!empty($daysTmp))
        {
            foreach ($daysTmp as $v) {
                $days[] = date("Y-m-d", $v);
            }
            $days =array_unique($days);
            $days = array_values($days);
            asort($days);
        }
        empty($days) && $days = array();
        return $days;
    }
    /*
     * 生成群组跑步里程排行榜（月/周）数据
     * @return
    */
    public function createGMRank($gid, $date)
    {
        $timeRange = $this->getDateRangeTime($date); // 获取该月/周 的开始与结束时间（时间戳）

        if($timeRange == false || !$gid)
        {
            return false;
        }

        extract($timeRange);
        $data = $this->db->getAll("select uid, sum(mileage) as mileage from r_group_run where gid = '{$gid}' and updatetime >= '{$start}' and updatetime < '{$end}' and is_delete = 0 group by uid");

        $redisKey = REDIS_PREFIX.'GMRank_'.$gid.'_'.$date;
        $this->redis->del($redisKey);
        if($data)
        {
            foreach ($data as $v)
            {
                $mileage = round($v['mileage'], 2);
                $this->redis->ZADD($redisKey, $mileage, $v['uid']);
            }
        }
        return true;
    }

    /*
     * 获取群组跑步里程排行榜（月/周）
     * @return
    */
    public function getGMRank($gid, $date)
    {
        $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GMRank_'.$gid.'_'.$date, '+inf', '-inf', array('withscores' => TRUE));
        if($result === false)
        {
            // // 生成群组跑步里程排行榜（月/周）
            $this->createGMRank($gid, $date);
    
            $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GMRank_'.$gid.'_'.$date, '+inf', '-inf', array('WITHSCORES' => 1));
        }
        if($result)
        {
            !isset($_ENV['client']) && $this->base->load('client');
            foreach($result as $uid => $m)
            {
                $userInfo = $_ENV['client']->getUserInfo($uid);
                $result[$uid] = array('uid' => $uid,
                                      'nickname' => $userInfo['nickname'],
                                      'header' => $userInfo['header'],
                                      'mileage' => round($m, 2),
                                      'level' => $userInfo['level']
                    );
            }
            $result = array_values($result);
        }
        empty($result) && $result = array();
        return $result;
    }
    /*
     * 获取群组跑步目标排行榜（月）
     * @return
    */
    public function getGTRank($gid, $date)
    {
        $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GTRank_'.$gid.'_'.$date, '+inf', '-inf', array('withscores' => TRUE));
        if($result)
        {
            foreach($result as $uid => $t)
            {
                $userInfo = $_ENV['client']->getUserInfo($uid);
                $mileage = $this->redis->ZSCORE(REDIS_PREFIX.'GMRank_'.$gid.'_'.$date,$uid);
                $result[$uid] = array('uid' => $uid,
                                      'nickname' => $userInfo['nickname'],
                                      'header' => $userInfo['header'],
                                      'mileage' => $mileage > 0 ? sprintf("%.2f",$mileage) : '0.00',
                                      'targetRate' => $t,
                                      'level' => $userInfo['level']
                    );
            }
            $result = array_values($result);
        }
        empty($result) && $result = array();
        return $result;
    }
    /*
     * 用户跑步数据
     * @return boolen
    */
    public function addGroupRunData($uid, $data = array())
    {
        $result = true;
        $groups = $this->myGroupList($uid, false);
        if(empty($groups) || empty($data))
            return $result;
        $time = time();
        $month = date("Y-m", $data['updatetime']);
        $week = date("YW", $data['updatetime']);
        // $week = common::getWeekth($data['updatetime']);
        $data['uid'] = $uid;
        $data['addtime'] = $time;
        foreach ($groups as $gid) {
            $data['gid'] = $gid;
            if($this->db->insertRowTable('r_group_run', $data))
            {
                $this->redis->HINCRBYFLOAT(REDIS_PREFIX.'GRTotal'.$month, $gid, $data['mileage']); // 群组月跑步总里程
                $this->redis->HINCRBYFLOAT(REDIS_PREFIX.'GRTotal'.$week, $gid, $data['mileage']);  // 群组周跑步总里程
                $this->redis->ZINCRBY(REDIS_PREFIX.'GMRank_'.$gid.'_'.$month, $data['mileage'], $uid); // 用户月跑步总里程
                $this->redis->ZINCRBY(REDIS_PREFIX.'GMRank_'.$gid.'_'.$week, $data['mileage'], $uid);   // 用户周跑步总里程
                $this->redis->HINCRBYFLOAT(REDIS_PREFIX.'GRTotal', $gid, $data['mileage']); // 群组跑步总里程
                $this->redis->ZINCRBY(REDIS_PREFIX."groupMileage", $data['mileage'], $gid); // 群组跑步总里程(排行榜)
                $this->redis->ZINCRBY(REDIS_PREFIX."MGRankList_".$uid , $data['mileage'], $gid); // 我的群组排名(排行榜)

                $this->record($gid,$data['mileage'],$uid,$data['updatetime']);
                $userTaget = $this->getUserTarget($gid, $uid, $month);
                if($userTaget > 0) // 个人月目标完成度
                {
                    $userMileage = $this->redis->ZSCORE(REDIS_PREFIX.'GMRank_'.$gid.'_'.$month,$uid);
                    $this->redis->ZADD(REDIS_PREFIX.'GTRank_'.$gid.'_'.$month, round($userMileage/$userTaget, 3), $uid);
                }
                $record = $this->getBestRecord($gid, false);
                $max = array('uid' => $uid,'updatetime' => $data['updatetime']);
                if(empty($record['farthest']) || $record['farthest']['value'] < $data['mileage'])
                {
                    $max['value'] = $data['mileage'];
                    $r = $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, 'farthest', json_encode($max));
                }
                if(empty($record['longest']) || $record['longest']['value'] < $data['elapsedtime'])
                {
                    $max['value'] = $data['elapsedtime'];
                    $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, 'longest', json_encode($max));
                }
                if($data['five_time'] > 0)
                {
                    if(empty($record['bestFive']) || $record['bestFive']['value'] > $data['five_time'])
                    {
                        $max['value'] = $data['five_time'];
                        $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, 'bestFive', json_encode($max));
                    }
                }
                if($data['ten_time'] > 0)
                {
                    if(empty($record['bestTen']) || $record['bestTen']['value'] > $data['ten_time'])
                    {
                        $max['value'] = $data['ten_time'];
                        $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, 'bestTen', json_encode($max));
                    }
                }
                if($data['half_mtime'] > 0)
                {
                    if(empty($record['bestHalf']) || $record['bestHalf']['value'] > $data['half_mtime'])
                    {
                        $max['value'] = $data['half_mtime'];
                        $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, 'bestHalf', json_encode($max));
                    }
                }
                if($data['mara_time'] > 0)
                {
                    if(empty($record['bestMara']) || $record['bestMara']['value'] > $data['mara_time'])
                    {
                        $max['value'] = $data['mara_time'];
                        $this->redis->hset(REDIS_PREFIX.'GRecord_'.$gid, 'bestMara', json_encode($max));
                    }
                }
                $this->createRecord($gid, 'maxTimes');
            }
        }
        return $result;
    }
    /*
     * 用户删除跑步数据
     * @return boolen
    */
    public function deleteRunData($uid, $data = array())
    {
        $result = false;
        $groups = $this->myGroupList($uid, false);
        if(empty($groups))
        {
            return $result;
        }

        // 参数校验
        if(empty($data) || !isset($data['did']) || !isset($data['updatetime']))
        {
            return $result;
        }
        // 日期
        $time = $this->base->time;
        $updatetime = $data['updatetime'];

        $did = $data['did'];
        foreach ($groups as $gid)
        {
            if($this->db->update("update r_group_run set is_delete = 1 where gid = '{$gid}' and did = '{$did}' and is_delete = 0"))
            {
                // 更新 群组跑步总里程
                $this->getGroupRunTotal($gid, 'all', $updatetime, true);
                // 更新 群组月跑步总里程
                $this->getGroupRunTotal($gid, 'month', $updatetime, true);
                // 更新 群组周跑步总里程
                $this->getGroupRunTotal($gid, 'week', $updatetime, true);

                // 更新 用户月跑步总里程
                $this->getUserRunTotal($gid, $uid, 'month', $updatetime, true);
                // 更新 用户周跑步总里程
                $this->getUserRunTotal($gid, $uid, 'week', $updatetime, true);

                // 更新个人月目标完成度
                $this->getUserTargetRank($gid, $uid, $updatetime);
                //更新群纪录

                $this->getBestRecord($gid);

                 //更新战力榜
                $datainfo=$this->base->load('run')->getRunDataByDid($did);
                $dataGRTotal = $datainfo['mileage'];

                $this->redis->hIncrBy(REDIS_PREFIX.'GRTotal',$gid, $dataGRTotal);

                //更新用户记录
                $this->base->load('run')->refreshUserRunRecord($uid);

                
                $recordArr = array('farthest','longest', 'bestFive', 'bestTen', 'bestHalf', 'bestMara','maxTimes');
                foreach ($recordArr as $v)
                {
                    $this->createRecord($gid, $v);
                }
            }
        }
        return $result;
    }

    /**
     * 发送IM群组消息
     * @param  array   $toUserId [接收人ID数组]
     * @param  [type]  $groupId  [群组ID]
     * @param  [type]  $desc     [内容]
     * @param  integer $type     [消息类型 0通知、1操作]
     * @return [type]            [description]
     */
    public function sendMessage($toUserId = array(), $groupId, $descType, $type = 0, $aid = '',$reason=''){
        foreach ($toUserId as $key => $value) {
            $category = "3";
            $send_id = "S10003";
            $source_id = $groupId; 
            $target_id = $value;

            $target_role = $this->getGroupRole($groupId, $value);
            $this->loginfo("sm-----1111--------".$target_role);

            $oper_id = $this->base->uid;

            $rId = $this->db->getOne("select id from r_group_add where gid = '{$groupId}' and uid = '{$oper_id}'");
            $this->loginfo("sm-----2222--------".$rId);
            $contentArr = array(
                "oper_id" => $oper_id,
                "target_role" => $target_role,
                "g_add_id" => $rId,
                'aid' => $aid,
                'reason' => $reason
            );
            $this->loginfo("sm-----3333--------".$value."&".$groupId."&".$descType);
            $content = json_encode($contentArr);
            $this->base->load('message')->insertMessage($category, $send_id ,$source_id ,$target_id ,$descType, $content, $type);
        }
    }

    /**
     * 更新操作类型消息状态
     * @param  [type] $categroy  [description]
     * @param  [type] $source_id [description]
     * @param  [type] $target_id [description]
     * @return [type]            [description]
     */
    public function updateMessage($categroy, $source_id, $target_ids = array(), $desc, $status = 1){
        foreach ($target_ids as $key => $target_id) {
            $this->base->load('message')->updateMessageByStatus($categroy, $source_id, $target_id ,$desc,$status);
        }
    }

    /**
     * 获取所有群组
     * @return [type] [description]
     */
    public function getAllGroupInfo(){
        return $this->db->getAll("select * from r_group where is_im = 0");
    }

    public function updateGroupStatus($gid){
        $sql = "update r_group set is_im = 1 where gid = '" . $gid . "'";
        return $this->db->update($sql);
    }

    /**
     * 根据群组ID获取该群组中的用户
     * 
     * @return [type] [description]
     */
    public function getUserInfoByGroupId($groupId){
        //群组中身份（群主，管理员，普通成员）
        //-1 非群组成员 0 普通成员 1 群组创建人 2 群组管理员 3 非群组成员（曾经是，被删除）
        return $this->db->getAll("select r_user.*,r_gmember.* from r_gmember left join r_user on r_gmember.uid = r_user.uid where role in ('0','1','2') and gid = '" . $groupId . "'");
    }



    public function getImUser($gid){
        //根据群组ID去mysql中查询数据,先去redis中获取数据,如果没有,则从数据库获取,数据库获取后放到redis中
        $all = $this->getGroupMember($gid);
        $allUser = array();
        foreach ($all as $key => $value) {
            $rst = $this->base->load('client')->getUserInfo($value);

            $user = array();
            $user['uid'] = $value;
            $user['nickname'] = isset($rst['nickname']) ? $rst['nickname'] : '';
            $user['header'] = isset($rst['header']) ? $rst['header'] : 0;
            array_push($allUser, $user);
        }
        return $allUser;
    }
    /**
     * 获取推荐群组的banners
     * @return array $bannerList
     */
    public function getRecommendBanner()
    {
        return $this->base->load('banner')->getGroupBanner();
    }
    /**
     * 获取推荐群组列表
     * @return array $groupList
     */
    public function getRecommendList($p = 1, $uid = 0, $limit = 20)
    {
        $redisKey = REDIS_PREFIX.'RecGroupList';
        $limit = intval($limit);
        $p = intval($p);

        if(!$this->redis->EXISTS($redisKey))
        {
            $this->updateGroupRecList();
        }
        if($uid > 0)
        {
            $p == 1 && $this->redis->del(REDIS_PREFIX.'MyRecGroupList_'.$uid);
            $redisKey = $this->getMyRecGroupList($uid, true);
        }

        $start = ($p-1) * $limit;
        $groupList = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => array($start, $limit-1)));

        empty($groupList) && $groupList = array();
        return $groupList;
    }
    /**
     * 更新推荐群组列表
     * @return array $groupList
     */
    public function updateGroupRecList()
    {
        $redisKey = REDIS_PREFIX.'RecGroupList';
        $this->redis->del($redisKey);

        $groupList = $this->db->getAll("select gid, add_time from r_group_recommend where is_delete = 0 order by add_time DESC");

        if($groupList)
        {
            foreach ($groupList as $v)
            {
                $this->redis->ZADD($redisKey, $v['add_time'], $v['gid']);
            }
        }
        
        return ;
    }
    /**
     * 更新我的推荐列表
     * @return string $tmpRedisKey
     */
    public function getMyRecGroupList($uid, $update = false, $expire = 1800)
    {
        $myRecGListKey = REDIS_PREFIX.'MyRecGroupList_'.$uid;
        if(!$this->redis->EXISTS($myRecGListKey))
        {
            $recGroupList = $this->getRecommendList(1, 0, 120);
            if($recGroupList)
            {
                if(!$this->redis->exists(REDIS_PREFIX.'MGListBR_'.$uid))
                {
                    $this->createMyGroupByRole($uid);
                }
                foreach ($recGroupList as $k => $gid)
                {
                    if($this->redis->ZRANK(REDIS_PREFIX.'MGListBR_'.$uid, $gid) === false)
                    {
                        $this->redis->ZADD($myRecGListKey, 200-$k, $gid);
                    }
                }
                $this->redis->EXPIRE($myRecGListKey, $expire);
            }
        }
        return $myRecGListKey;
    }
    /**
     * 更新我的群组列表
     * @return var
     */
    public function createMyGroupByRole($uid)
    {
        if(!$uid)
        {
            return;
        }
        $redisKey = REDIS_PREFIX.'MGListBR_'.$uid;
        $this->redis->del($redisKey);

        $data = $this->db->getAll("select gid, lastupdate, role from r_gmember where uid = '{$uid}' and role >=0 && role < 3 order by lastupdate DESC");
        if(!empty($data))
        {
            foreach ($data as $v) {
                $gInfo = $this->getGroupInfo($v['gid']);
                if($gInfo && $gInfo['isDismiss'] == 0)
                {
                    $score = $v['role'] == 1 ? 3000000000 : ($v['role'] == 2 ? 1000000000 : 0);
                    $score += $v['lastupdate'];
                    $this->redis->ZADD($redisKey, $score, $v['gid']);
                }
            }
        }
        return ;
    }
    /**
     * 获取用户在上马活动期间（5.17-5.24）, 在群组中跑步里程
     * @return var
     */
    public function getShMarathonMileage($uid, $gid)
    {
        $mileage = 0;
        if(!$uid || !$gid)
        {
            return $mileage;
        }

        $start = strtotime('2015-05-17');
        $end = strtotime('2015-05-25');

        $mileage = $this->db->getOne("select sum(mileage) from r_group_run where gid = '{$gid}' and uid = '{$uid}' and is_delete = 0 and updatetime >= '{$start}' and updatetime < '{$end}'");

        $mileage = sprintf("%.2f", $mileage);

        return $mileage;
    }
    /**
     * 获取某时间段内群组成员的跑步里程
     * @return var
     */
    public function getMemberRunDataByTime($uid, $gid, $start = 0, $end = 0)
    {
        $mileage = 0;
        if(!$uid || !$gid)
        {
            return $mileage;
        }

        $start = empty($start) ? strtotime('2015-05-17') : $start;
        $end = empty($start) ? strtotime('2015-05-25') : $end;

        $dids = $this->db->getCol("select distinct(did) from r_group_run where gid = '{$gid}' and uid = '{$uid}' and updatetime >= '{$start}' and updatetime < '{$end}' and 180 * mileage <= elapsedtime");
        if(!empty($dids))
        {
            $mileage = $this->db->getOne("select sum(mileage) from r_data where did ".$this->base->load('push')->db_create_in($dids)." and is_delete = 0 and overSpeed = 0");
        }

        $mileage = sprintf("%.2f", $mileage);

        return $mileage;
    }
    /**
     * 根据用户加入时间， 获取群组成员列表
     *  int $gid
     *  int $deadline  加入群组的截止时间
     * @return array
     */
    public function getGroupMemberByDeadline($gid, $deadLine = 0)
    {
        $gid = intval($gid);
        empty($deadLine) && $deadLine = time();

        $members = array();

        $gInfo = $this->getGroupInfo($gid);
        if(empty($gInfo) || $gInfo['isDismiss'] == 1)
        {
            return $members;
        }

        $members = $this->db->getCol("select uid from r_gmember where gid = '{$gid}' and role in ('0','1','2') and addtime < '{$deadLine}'");
        
        return $members;
    }

    /**
     * 根据日期获取该周/月所在的开始时间和结束时间
     * @return var
     */
    public function getDateRangeTime($date)
    {
        $isMonth = strpos($date,'-') !== false ? 1 : 0;

        if($isMonth)
        {
            if(!preg_match('/\d{4}-\d{2}/', $date))
              return false;
        }
        elseif(!preg_match('/\d{6}/', $date))
        {
            return false;
        }

        // 如果为周， 转换日期为 strtotime 函数可以识别的 格式（年-W周）
        if(!$isMonth)
        {
            $date = str_replace(substr($date, 0,4), substr($date, 0,4).'-W', $date);
        }

        $start = strtotime($date);
        if(!$start)
        {
            return false;
        }

        if($isMonth)
        {
            $end = strtotime("next Month", $start);
        }
        else
        {
            $end = $start + 86400 * 7;
        }
        return compact('start', 'end');
    }

    /**
     * 获取群组跑步里程
     * @param int $gid 群组id
     * @param string $type 里程类型  month:月里程， week: 周里程， all:总里程
     * @param int $runTime  跑步时间
     * @param boolen $update  是否更新
     * @param
    */
    public function getGroupRunTotal($gid, $type = 'all', $runTime = 0, $update = false)
    {
        $result = 0.00;

        // 里程类型集合
        $typeArr = array('all', 'month', 'week');
        !$runTime && $runTime = $this->base->time;

        if(!$gid || !in_array($type, $typeArr))
        {
            return false;
        }

        // redids key
        $redisKey = REDIS_PREFIX.'GRTotal';
        if($type == 'month')
        {
            $month = date("Y-m", $runTime);
            $redisKey .= $month;
        }
        else if($type == 'week')
        {
            $week = date("YW", $runTime);
            $redisKey .= $week;
        }

        if($this->redis->HEXISTS($redisKey, $gid) === false || $update)
        {
            switch ($type) {
                case 'all':
                    $mileage = $this->db->getone("select sum(mileage) from r_group_run where gid = '{$gid}' and is_delete = 0");
                    $result = sprintf("%.2f", $mileage);
                    $this->redis->zadd(REDIS_PREFIX."groupMileage", $result, $gid); // 群组跑步总里程(排行榜)
                    $this->redis->zadd(REDIS_PREFIX."MGRankList_".$this->base->uid , $result, $gid); // 我的群组排名(排行榜)
                    break;
                case 'month':
                    // 计算开始与结束的时间
                    $startTime = strtotime($month);
                    $endTime = $startTime + date("t", $runTime) * 86400;

                    $mileage = $this->db->getone("select sum(mileage) from r_group_run where gid = '{$gid}' and is_delete = 0 and updatetime >= '{$startTime}' and updatetime < '{$endTime}'");
                    $result = sprintf("%.2f", $mileage);
                    break;
                case 'week':
                    // 计算开始与结束的时间
                    $startTime = strtotime(date("Y-\WW", $runTime));
                    $endTime = $startTime + 7 * 86400;

                    $mileage = $this->db->getone("select sum(mileage) from r_group_run where gid = '{$gid}' and is_delete = 0 and updatetime >= '{$startTime}' and updatetime < '{$endTime}'");
                    $result = sprintf("%.2f", $mileage);
                    break;
                default:
                    return false;
                    break;
            }

            $this->redis->hset($redisKey, $gid, $result);
        }
        else
        {
            $result = $this->redis->hget($redisKey, $gid);
        }
        return $result;
    }
    /**
     * 获取用户在某群组中跑步总里程
     * @param int $gid 群组id
     * @param int $uid 用户id
     * @param string $type 里程类型  month:月里程， week: 周里程， all:总里程
     * @param int $runTime  跑步时间
     * @param boolen $update  是否更新
     * @param return string $mileage
    */
    public function getUserRunTotal($gid, $uid, $type = 'all', $runTime = 0, $update = false)
    {
        $result = 0.00;

        // 里程类型集合
        $typeArr = array('month', 'week');
        if(!$gid || !$uid || !in_array($type, $typeArr))
        {
            return false;
        }

        !$runTime && $runTime = $this->base->time;

        // redids key
        $redisKey = REDIS_PREFIX.'GMRank_'.$gid.'_';
        if($type == 'month')
        {
            $month = date("Y-m", $runTime);
            $redisKey .= $month;
        }
        else
        {
            $week = date("YW", $runTime);
            $redisKey .= $week;
        }

        $result = $this->redis->zscore($redisKey, $uid);
        if($this->redis->zscore($redisKey, $uid) === false || $update)
        {
            switch ($type) {
                case 'month':
                    // 计算开始与结束的时间
                    $startTime = strtotime($month);
                    $endTime = $startTime + date("t", $runTime) * 86400;

                    $mileage = $this->db->getone("select sum(mileage) from r_group_run where gid = '{$gid}' and uid = '{$uid}' 
                                        and is_delete = 0 and updatetime >= '{$startTime}' and updatetime < '{$endTime}'");
                    $result = sprintf("%.2f", $mileage);
                    break;
                case 'week':
                    // 计算开始与结束的时间
                    $startTime = strtotime(date("Y-\WW", $runTime));
                    $endTime = $startTime + 7 * 86400;

                    $mileage = $this->db->getone("select sum(mileage) from r_group_run where gid = '{$gid}' and uid = '{$uid}' 
                                        and is_delete = 0 and updatetime >= '{$startTime}' and updatetime < '{$endTime}'");
                    $result = sprintf("%.2f", $mileage);
                    break;
                default:
                    return false;
                    break;
            }

            $this->redis->zadd($redisKey, $result, $uid);
        }

        return $result;
    }
    /**
     * 获取用户在某群组中的目标排行榜
     * @param int $gid 群组id
     * @param int $uid 用户id
     * @param int $time  时间
     * @param boolen $update  是否更新
     * @param return string $target_rate
    */
    public function getUserTargetRank($gid, $uid, $time = 0, $update = false)
    {
        $target_rate = 0.000;
        if(!$gid || !$uid)
        {
            return $target_rate;
        }

        !$time && $time = $this->base->time;
        $month = date("Y-m", $time);
        // redids key

        $redisKey = REDIS_PREFIX.'GTRank_'.$gid.'_'.$month;

        $target_rate = $this->redis->zscore($redisKey, $uid);
        if($target_rate === false)
        {
            $target = $this->getUserTarget($gid, $uid, $month);  // 个人月目标
            if($target > 0)
            {
                $mileage = $this->getUserRunTotal($gid, $uid, 'month', $time);
                $target_rate = sprintf("%.3f", $mileage/$target);

                $this->redis->ZADD($redisKey, $target_rate, $uid);
            }
        }

        !$target_rate && $target_rate = 0.000;
    }

    /**
     * 获取指定群组，指定时间的跑步数据
     * @param int $gid  群组ID
     * @param int $bgTime,$edTime 开始和结束时间
     * @return  $runDate   群组跑步数据
     */

    public function getGroupInfoByDay($gid,$bgTime,$endTime)
    {

        $runDate = array();

        if(empty($gid)||empty($bgTime)||empty($endTime))
        {
            return $runDate;
        }

        $runDate = $this->db->getRow("select gid,sum(mileage) as mileage,count(did) as times,count(distinct uid) as members from r_group_run where gid = '{$gid}' and updatetime >='{$bgTime}' AND updatetime <='{$endTime}' and 180 * mileage <= elapsedtime and addtime <='{$endTime}'");
        if(!empty($runDate))
        {
            $runDate['mileage'] = sprintf("%.2f",$runDate['mileage']);
        }
       
        return $runDate;

    }


    /**
     * 统计指定活动时间的参加人数
     * @param int $groups  活动群组
     * @param int $bgTime,$edTime 活动开始和结束时间
     * @return  $countUid   统计人数
     */

    public function getActivityUids($groups,$bgTime,$endTime)
    {

        $countUid = 0;

        if(empty($groups)||empty($bgTime)||empty($endTime))
        {
            return $countUid;
        }

        $countUid = $this->db->getOne("select count(distinct(uid)) from r_group_run where gid ".$this->base->load('push')->db_create_in($groups)."and updatetime >= $bgTime and updatetime <= $endTime");

        return $countUid;

    }

    /**
     * 获取用户待验证群组
     * @param $uid
     * @return mixed
     */
    public function getVerifyByUid($uid){
        if(empty($uid)) return array();
        $sql = "select gid from r_group_add where status=1 and uid='$uid' and isShow=1";
        $gids = $this->db->getAll($sql);
        $reData = array();
        $k = 0;
        foreach($gids as $info){
            $gInfo = $this->getGroupInfo($info['gid']);
            if($gInfo['isDismiss'] == 0 ){
                $reData[$k]['gid'] = $gInfo['gid'];
                $reData[$k]['name'] = $gInfo['name'];
                $reData[$k]['header'] = $gInfo['header'];
                $reData[$k]['slogan'] = $gInfo['slogan'];
                $reData[$k]['role'] = $this->getGroupRole($gInfo['gid'], $uid);
                $act = $this->base->load('groupActivity')->getIngAct($gInfo['gid'],0,5);
                $reData[$k]['isActivity'] = empty($act) ? 0 : 1;
                $reData[$k]['totalMileage'] = floatval($this->getTotalMileageByGid($gInfo['gid']));
                $reData[$k]['authenticate'] = $this->isAuth($gInfo['gid']);
                $reData[$k]['num'] = $gInfo['members'];
                $reData[$k]['status'] = 1;
                $k++;
            }
        }
        return $reData;
    }

    /**
     * 通过gid获取群总跑步里程
     * @param $gid
     * @return mixed
     */
    public function getTotalMileageByGid($gid){
        $redisKey = REDIS_PREFIX."groupMileage";//群跑步总里程
        $totalMileage = $this->redis->zscore($redisKey,$gid);
        if(empty($totalMileage)){
            $sql = "select sum(mileage) from r_group_run where gid=$gid and is_delete=0";
            $totalMileage = $this->db->getOne($sql);
            $this->redis->zadd($redisKey,$totalMileage,$gid);
        }
        return $totalMileage;

    }

    /**
     * 根据不同类型获取相应的群组id
     * @param $type 群组类型 2：认证  3：同城
     * @param string $city
     * @param int $page
     * @return mixed
     */
    public function getGroupByType($type,$city='',$page=1){
//        if($type == 3){
//            $key = REDIS_PREFIX."CityGroup".base64_encode($city);
//            $gids = $this->redis->sRandMember($key,15);
//            return $gids;
//        }
//        $reData = array();
        $listRow = 20;
        if($type == 2){ //认证
            $sql = "select gid from r_group_auth where status=1 ";
            $field = "add_time";
        }
        if($type == 3){ //同城
            $sql = "select gid from r_group where (city='$city' or province='$city') and isDismiss = 0 ";
            $field = "members";
        }
        $offset = ($page-1) * $listRow;
        $sql .= " order by $field desc limit {$offset},{$listRow}";
        $info = $this->db->getAll($sql);
        $reData = array();
        if(!empty($info)){
            foreach($info as $info){
                $reData[] = $info['gid'];
            }
        }

        return $reData;
    }

    /**
     * 获取用户未加入的群组
     * @param $uid
     * @return array
     */
    public function getGroupByUid($uid){
        $redisKey = REDIS_PREFIX."groupMileage";
        $data = $this->redis->ZREVRANGE($redisKey,0,100);
        $gids = array();
        foreach($data as $gid){
            $status = $this->getGroupStatus($uid,$gid);
            $members = intval($this->redis->hget(REDIS_PREFIX."GroupInfo_".$gid,'members'));
            $maxMember = $this->base->config['group']['maxMember'];
            if($status != 7 || ($members+5) >= $maxMember){
                continue;
            }
            $gids[] = $gid;
        }
        return $gids;
    }

    /**
     * 群是否认证
     * @param $gid
     * @return int
     */
    public function isAuth($gid){
        $sql = "select gid from r_group_auth where gid=$gid and status=1";
        $info = $this->db->getOne($sql);
        return empty($info) ? 0 : 1;
    }

    /**
     * 获取我的群组排行
     * @param $uid
     * @param int $gid
     * @param string $direc
     * @param int $offset
     * @return mixed
     */
    public function getMGrank($uid,$gid=0,$direc='next',$offset=20){
        $redisKey = REDIS_PREFIX."MGRankList_".$uid;
        $start = 0;
        $limit = $offset-1;
        if($gid > 0){
            $start = $this->redis->zrevrank($redisKey,$gid)+1;
            $limit = $start + $offset;
        }
        return $this->redis->zrevrange($redisKey,$start,$limit,true);

    }

    /**
     * 获取群帖子列表
     * @param $gid
     * @param int $news_id
     * @param string $direc
     * @param int $offset
     * @return mixed
     */
    public function getPostByGid($gid,$news_id=0,$direc='next',$offset=20){
        $key = REDIS_PREFIX.'GroupNews_'.$gid;
        if($this->redis->exists($key)){
            if($news_id == 0){
                $start = 0;
                $end = $offset-1;
            }else{
                $start = $this->redis->zrevrank($key,$news_id)+1;
                $end = $start + $offset - 1;
            }
            $result = $this->redis->zrevrange($key,$start,$end);

        }else{
            $sql = "select news_id from r_group_news where gid=$gid and is_top=0 and is_show=1";
            if($news_id>0){
                $sql .= " and news_id ";
                $sql .= $direc == 'prev' ? "> {$news_id} order by news_id ASC" : "< {$news_id} ORDER BY news_id DESC limit $offset";
            }
            else
            {
                $sql .= " ORDER BY news_id DESC limit $offset";
            }
            $result = $this->db->getALl($sql);
        }
        return $result;

    }

    /**
     * 获取帖子信息
     * @param $news_id
     * @param $gid
     * @return mixed
     */
    public function getNews($news_id,$gid=0){
        if($gid == 0){
            $sql = "select * from r_group_news where news_id ='$news_id' and is_show=1";
            return $this->db->getAll($sql);
        }else{
            $sql = "select * from r_group_news where news_id ='$news_id' and gid='$gid' and is_show=1";
            return $this->db->getRow($sql);
        }

    }

    /**
     * 获取认证群组信息
     * @param $gid
     * @return mixed
     */
    public function getAuthGroup($gid){
        $sql = "select * from r_group_auth where gid = $gid";
        return $this->db->getRow($sql);
    }

    /**
     * 获取置顶的帖子id
     * @param $gid
     * @return mixed
     */
    public function getTopNews($gid){
        $sql = "select news_id from r_group_news where gid=$gid and is_top=1 and is_show = 1";
        return $this->db->getOne($sql);
    }

    /**
     * 检测是否为置顶帖子
     * @param $news_id
     * @return mixed
     */
    public function getTopByNewsId($news_id,$gid){
        $sql = "select news_id from r_group_news where news_id='$news_id' and gid='$gid' and is_top=1 and is_show = 1";
        return $this->db->getOne($sql);
    }

    public function transfer($gid,$auid,$uid){
        $time = $this->base->time;
        $this->db->query("update r_group set uid=$auid where gid=$gid");
        $this->redis->hset(REDIS_PREFIX."GroupInfo_$gid",'uid',$auid);
        //更改角色
        $this->db->query("update r_gmember set role=0 where gid=$gid and uid=$uid");
        $this->db->query("update r_gmember set role=1 where gid=$gid and uid=$auid");
        //创建群组数变更
        $this->redis->HINCRBY(REDIS_PREFIX.'GroupCreateNum', $uid, -1); // 用户创建群组数-1
        $this->redis->HINCRBY(REDIS_PREFIX.'GroupCreateNum', $auid, 1); // 用户创建群组数+1
        //更改群主
        $this->redis->hset(REDIS_PREFIX.'GroupHost', $gid, $auid);
        $times = $this->redis->zscore(REDIS_PREFIX.'MGListBR_'.$uid,$gid);
        $this->redis->zadd(REDIS_PREFIX.'MGListBR_'.$auid, $time + 3000000000, $gid);
        $this->redis->zadd(REDIS_PREFIX.'MGListBR_'.$uid, $times - 3000000000, $gid);
        //更换身份
        $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, $time * 3, $auid); //加入群成员列表
        $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, $time, $uid); //加入群成员列表
        $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $auid, 1); //群成员身份标识
        $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$gid, $uid, 0); //群成员身份标识
        $this->sendMessage(array($auid),$gid,"G19");
        $ltime = $time + 7200;
        $aids = $this->db->getAll('select aid from r_group_activity where status=0 and gid='.$gid.' and stime >'.$ltime);
        if(!empty($aids)){
            foreach($aids as $aid){
                $this->db->query('update r_group_activity set status=1 where aid='.$aid['aid']);
                $this->redis->zrem(REDIS_PREFIX.'GroupActivity_'.$gid,$aid['aid']);
                //$this->redis->zrem(REDIS_PREFIX.'GroupActivity',$aid['aid']);
            }
        }

    }

    public function getNewsNum($gid){
        $sql = "select count(*) from r_group_news where gid=$gid and is_show=1";
        return $this->db->getOne($sql);
    }

    /**
     * 记录群组活动信息
     * @param $gid
     * @param $m
     * @param $uid
     * @param $updatetime 跑步提交时间
     */
    public function record($gid,$m,$uid,$updatetime){
        $time = time();
        $aids = $this->redis->zrevrange(REDIS_PREFIX."GroupActivity_".$gid,0,-1);
        if(!empty($aids)){
            foreach($aids as $aid){
                $aInfo = $this->base->load("groupActivity")->getActByAid($aid);
                if($aInfo['stime'] <= $updatetime && $aInfo['etime'] > $updatetime && $this->base->load('groupActivity')->isJoin($aid,$uid,$gid)){
                    if(in_array($aInfo['type'],[3,4]) && $this->redis->sismember(REDIS_PREFIX."ACTaccept_".$aid,$gid)){
                        $this->redis->ZINCRBY(REDIS_PREFIX.'GroupAct_'.$aid,$m,$gid);//参加官方活动群组累计公里数
                    }
                    $this->redis->ZINCRBY(REDIS_PREFIX.'GARecord_'.$gid."_".$aid,$m,$uid);
                    $date = date("Ymd",$updatetime);
                    $this->redis->hIncrByFloat(REDIS_PREFIX."UDPerDay_".$uid."_".$aid."_".$gid,$date,$m);
                    if($aInfo['days'] > 0){
                        $mileage = $this->redis->hget(REDIS_PREFIX."UDPerDay_".$uid."_".$aid."_".$gid,$date);
                        if($mileage >= $aInfo['target'] && !$this->redis->get(REDIS_PREFIX."ActRecord_".$aid."_".$gid."_".$uid)){
                            $this->redis->ZINCRBY(REDIS_PREFIX.'GADay_'.$gid."_".$aid,1,$uid);
                            $expireTime = strtotime(date('Y-m-d 23:59:59',$updatetime)) - $time;
                            $expireTime >= 10 && $this->redis->setex(REDIS_PREFIX."ActRecord_".$aid."_".$gid."_".$uid,$expireTime,1);
                        }
                    }
                }
            }
        }

    }

    /**
     * 获取同城群组key
     * @param $province
     * @param $city
     * @return bool|string
     */
    public function getCityKey($province,$city){
        if(empty($province) && empty($city)){
            return false;
        }
        $specialCity = ['上海','北京','重庆','天津','香港','澳门','台湾'];
        $rediskey = REDIS_PREFIX."CityGroup";
        if(in_array($province,$specialCity)){
            $cityKey = base64_encode($province);
        }else{
            $cityKey = base64_encode($city);
        }
        return $rediskey.$cityKey;
    }

    /**
     * 统计群组男性人数以及群成员信息
     * @param $gid
     * @return array
     */
    public function groupStatic($gid){
        $members = $this->db->getAll("select u.gender,g.uid,u.header from r_group_add g left join r_user u on g.uid=u.uid where gid={$gid} and status=0 and gender != 1 limit 7");
        foreach($members as &$item){
            $item['gender'] = 2;
        }
        $count = count($members);
        $m = [];
        if($count < 7){
            $m = $this->db->getAll("select u.gender,g.uid,u.header from r_group_add g left join r_user u on g.uid=u.uid where gid={$gid} and status=0 and gender = 1 limit 7");
        }
        $members = array_merge($members,$m);
        $maleNum = $this->db->getOne("select count(*) from r_group_add g left join r_user u on g.uid=u.uid where gid={$gid} and status=0 and gender=1");
        return compact('members','maleNum');
    }
}
?>
